package com.runvp.common.util.enc;

import com.runvp.common.hex.HexConvert;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

public class AESGCMDecryption {
    public static void main(String[] args) throws Exception {
        // 16进制字符串示例
        String hexString = HexConvert.str2HexStr("BMrcujdO0XDjvOOa"); // 替换为您的16进制字符串
        byte[] keyBytes = hexStringToByteArray(hexString);
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

        // 解密
        String encryptedHexString = "6BE3153AFC79025ACDF03CB38D988927BBF1DB4FCE387729CB19AB13FEC136"; // 替换为您的加密后的16进制字符串
        byte[] encryptedBytes = hexStringToByteArray(encryptedHexString);
        byte[] nonce = Arrays.copyOfRange(encryptedBytes, 0, 12);
        byte[] encryptedContent = Arrays.copyOfRange(encryptedBytes, 12, encryptedBytes.length);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, nonce));
        byte[] decryptedBytes = cipher.doFinal(encryptedContent);

        String decryptedString = new String(decryptedBytes, StandardCharsets.UTF_8);
        System.out.println("Decrypted String: " + decryptedString);
    }

    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}